/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.config.client.config;

import com.alibaba.fastjson.JSONObject;
import com.config.client.cache.ConfigCache;
import com.utils.HttpClientUtils;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ConcurrentReferenceHashMap;

import java.util.LinkedHashMap;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for {@link MessageSource}.
 *
 * @author Dave Syer
 * @author Phillip Webb
 * @author Eddú Meléndez
 * @since 1.5.0
 */
@Configuration
@AutoConfigureOrder(-1)
@Conditional(InitCloudConfig.ResourceBundleCondition.class)
@EnableConfigurationProperties
public class InitCloudConfig {

    private static final Resource[] NO_RESOURCES = {};


    /**
     * 参照MessageSourceAutoConfiguration类
     * 先执行配置中心的获取
     * 自动装配顺序：AutoConfigurationImportSelector-->public Iterable<Entry> selectImports()
     * 自动装配JDBC：DataSourceAutoConfiguration类下
     */
    protected static class ResourceBundleCondition extends SpringBootCondition{

        private static ConcurrentReferenceHashMap<String, ConditionOutcome> applicationName = new ConcurrentReferenceHashMap<>();
        @Override
        public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
            ConfigCache configCache = ConfigCache.getInstance();
            // 获取服务名
            String serverName = context.getEnvironment().getProperty("spring.application.name");
            // 获取自己写的注册/配置中心地址cloudConfig(ip:pord)的形式
            String configCentreAddress = context.getEnvironment().getProperty("cloud.server.server-ip");
            // 发送http请求(ip:pord)形式
            String httpUrl = "http://" + configCentreAddress + ":8848" + "/client_first_start_pull_config?serverName=" + serverName;
            JSONObject result = HttpClientUtils.httpGet(httpUrl);
            configCache.setMd5(result.get("md5") != null ? result.get("md5").toString() : null);
            configCache.setConfigId(result.get("id") != null && result.get("id") != "" ? (Integer) result.get("id") : null);
            configCache.setValue(result.get("value") != null ? result.get("value").toString() : null);
            Object configValue = result.get("configValue");
            LinkedHashMap<String, Object> linkedHashMap = JSONObject.parseObject(JSONObject.toJSONString(configValue), LinkedHashMap.class);
            linkedHashMap.forEach((k,v)->{
                System.setProperty(k, v != null ? v.toString() : null);
            });

            ConditionOutcome outcome = applicationName.get(serverName);
            if (outcome == null) {
                outcome = new ConditionOutcome(serverName != null, serverName);
                applicationName.put(serverName, outcome);
            }
            return outcome;
        }


    }


}
